package com.zmzncs.lmtc.module.customer.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmzncs.lmtc.common.interactive.mp.MpMessage;
import com.zmzncs.lmtc.common.pojo.PageInfo;
import com.zmzncs.lmtc.common.pojo.mpMessage.GiveTicketMessage;
import com.zmzncs.lmtc.common.util.DateTimeUtil;
import com.zmzncs.lmtc.common.util.JsonUtil;
import com.zmzncs.lmtc.module.customer.dao.CustomerDao;
import com.zmzncs.lmtc.module.customer.pojo.cust_info.CustInfo;
import com.zmzncs.lmtc.module.customer.pojo.cust_ticket.*;
import com.zmzncs.lmtc.module.customer.dao.CustTicketDao;
import com.zmzncs.lmtc.module.customer.pojo.customer.CustomerDTO;
import com.zmzncs.lmtc.module.customer.service.CustInfoService;
import com.zmzncs.lmtc.module.customer.service.CustTicketService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.module.promotion.dao.TicketDao;
import com.zmzncs.lmtc.module.promotion.pojo.ticket.Ticket;
import com.zmzncs.lmtc.module.shop.dao.ShopOrderDao;
import com.zmzncs.lmtc.module.shop.dao.ShopTicketFileDao;
import com.zmzncs.lmtc.module.shop.pojo.shop_order.ShopOrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.InvalidApplicationException;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2020-10-13
 */
@Slf4j
@Service
public class CustTicketServiceImpl extends ServiceImpl<CustTicketDao, CustTicket> implements CustTicketService {

    @Autowired
    CustTicketDao custTicketDao;
    @Autowired
    TicketDao ticketDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    CustInfoService custInfoService;
    @Autowired
    MpMessage mpMessage;
    @Autowired
    ShopTicketFileDao shopTicketFileDao;
    @Autowired
    ShopOrderDao shopOrderDao;

    /**
     * 条件分页查询优惠券使用详情
     */
    @Override
    public Map<String,Object> getTicketUseInfo(Page page, Long ticketId) {
        Map<String,Object> map = new HashMap<>();
        IPage<CustTicketDTO> custTicketDTOIPage = custTicketDao.getTicketUseInfo(page, ticketId);
        List<CustTicketDTO> records = custTicketDTOIPage.getRecords();
        if (records != null && !records.isEmpty()){
            for (CustTicketDTO dto : records) {
                Integer grantType = dto.getGrantType();
                Date useBeginTime = dto.getUseBeginTime();
                Date useEndTime = dto.getUseEndTime();
                Date receiveTime = dto.getReceiveTime();
                if (grantType == 1){
                    //平台发放
                    dto.setGrantTime(DateTimeUtil.convertYMDHMS(receiveTime));
                } else {
                    //活动发放
                    dto.setGrantTime(DateTimeUtil.convertYMDHMS(useBeginTime) + "至" + DateTimeUtil.convertYMDHMS(useEndTime));
                }
            }
        }
        PageInfo<CustTicketTableVO> iPage = JsonUtil.pageTransform(custTicketDTOIPage, CustTicketTableVO.class);
        //根据券Id统计总领取和总使用数量
        CustTicketDTO ticketDTO = custTicketDao.sumTicketInfo(ticketId);
        Long sumReceived = ticketDTO.getSumReceived();
        Long sumUsed = ticketDTO.getSumUsed();
        map.put("iPage",iPage);
        map.put("sumReceived",sumReceived);
        map.put("sumUsed",sumUsed);
        return map;
    }

    /**
     * 发放优惠券
     */
    @Override
    @Transactional
    public void grantTicket(CustTicketGrantForm form) {
        Integer grantType = form.getGrantType();
        List<CustTicketGrantForm.TicketInfo> ticketList = form.getTicketList();
//        Date grantTime = DateTimeUtil.getDayStart(DateTimeUtil.fomatDateTime(form.getGrantTime()));
        List<Long> custIdList = form.getCustomerIds();

        //  个人
        if ( grantType != null && 1 == grantType){
            //  客户列表
            for (Long customerId : custIdList) {
                Integer ticketCount = 0;
                //  优惠券列表
                for (CustTicketGrantForm.TicketInfo ticketInfo : ticketList) {
                    //  统计给客户发放的总数量
                    ticketCount += ticketInfo.getCount();
                    //  查询优惠券
                    Ticket ticket = ticketDao.selectById(ticketInfo.getTicketId());
                    //  添加客户优惠券
                    for(int i=0; i<ticketInfo.getCount(); i++){
                        CustTicket custTicket = new CustTicket();
                        BeanUtils.copyProperties(ticket, custTicket);
                        custTicket.setId(null);
                        custTicket.setStatus(0);
                        custTicket.setTicketId(ticketInfo.getTicketId());   //  优惠券id
                        custTicket.setGrantType(1); //  发放类型，1平台发放，2活动发放
                        custTicket.setUseType(ticketInfo.getUseType()); //  使用类型，1.通用 2.时长 3.月租 4.充值
                        custTicket.setUseBeginTime(form.getGrantTime());  //  使用开始时间
                        custTicket.setUseEndTime(DateTimeUtil.getDayEnd(DateTimeUtil.getNextDayDate(form.getGrantTime(), ticketInfo.getExpiryDays())));   //  使用结束时间
                        custTicket.setReceiveTime(form.getGrantTime());   //  领取时间
                        custTicket.setCustomerId(customerId);   //  客户id
                        custTicketDao.insert(custTicket);
                    }
                }

                //  会员信息
                CustInfo custInfo = custInfoService.getById(customerId);

                //优惠券微信公众号信息
                if (custInfo != null && custInfo.getUnionid() != null){
                    GiveTicketMessage message = new GiveTicketMessage();
                    message.setUnionid(custInfo.getUnionid());
                    message.setCount(ticketCount.toString());
                    message.setGiveTime(DateTimeUtil.getTime());
                    //优惠券发放通知
                    mpMessage.giveTicketMessage(message);
                }
            }
        //群体
        } else if(grantType!=null && 2 == grantType){
            Integer memberType = form.getMemberType();
            if (memberType == 2) {
                memberType = null;
            }
            //  查询会员
            List<CustomerDTO> customerDTOList = customerDao.getInfoByMemberType(memberType);
            if (customerDTOList != null && !customerDTOList.isEmpty()){
                //  客户列表
                for (CustomerDTO customerDTO : customerDTOList) {
                    //  给客户发放的总数量
                    Integer ticketCount = 0;
                    //  优惠券
                    for (CustTicketGrantForm.TicketInfo ticketInfo : ticketList) {
                        //  统计给客户发放的总数量
                        ticketCount += ticketInfo.getCount();
                        //  查询优惠券
                        Ticket ticket = ticketDao.selectById(ticketInfo.getTicketId());
                        //  添加客户优惠券
                        for(int i=0; i<ticketInfo.getCount(); i++) {
                            CustTicket custTicket = new CustTicket();
                            BeanUtils.copyProperties(ticket, custTicket);
                            custTicket.setId(null);
                            custTicket.setStatus(0);
                            custTicket.setTicketId(ticketInfo.getTicketId());
                            custTicket.setGrantType(1); //  发放类型，1平台发放，2活动发放
                            custTicket.setUseType(ticketInfo.getUseType());
                            custTicket.setUseBeginTime(form.getGrantTime());
                            custTicket.setUseEndTime(DateTimeUtil.getDayEnd(DateTimeUtil.getNextDayDate(form.getGrantTime(), ticketInfo.getExpiryDays())));
                            custTicket.setReceiveTime(form.getGrantTime());
                            custTicket.setCustomerId(customerDTO.getId());
                            custTicketDao.insert(custTicket);
                        }
                    }

                    //优惠券微信公众号信息
                    if (customerDTO != null && customerDTO.getUnionid() != null){
                        GiveTicketMessage message = new GiveTicketMessage();
                        message.setUnionid(customerDTO.getUnionid());
                        message.setCount(ticketCount.toString());
                        message.setGiveTime(DateTimeUtil.getTime());
                        //优惠券发放通知
                        mpMessage.giveTicketMessage(message);
                    }
                }
            }
        }else{
            log.info("--------发放优惠券失败-----------");
        }
    }

    @Override
    public IPage<CustTicketDTO> getShopTicketPage(CustTicketShopSelectForm form) {
        IPage<CustTicketDTO> iPage = custTicketDao.getShopTicketPage(form.getPage(),form);
        if (iPage != null && iPage.getRecords() != null && iPage.getRecords().size() > 0){
            for (CustTicketDTO ticketDTO : iPage.getRecords()) {

                Date useEndTime = ticketDTO.getUseEndTime();
                if (new Date().getTime() > useEndTime.getTime()){
                    ticketDTO.setStatus(2);
                }

                Long ticketId = ticketDTO.getTicketId();
                List<String> urlList = shopTicketFileDao.getfileByTicketId(ticketId);
                if (urlList != null && urlList.size() > 0){
                    ticketDTO.setFileUrl(urlList.get(0));
                }

                //已使用商户优惠券购买商品信息
                if (ticketDTO.getStatus().equals(1)){
                    ShopOrderDTO shopOrderDTO = shopOrderDao.getOrderInfoByTicketId(ticketDTO.getId());
                    if (shopOrderDTO != null){
                        ticketDTO.setGoodsName(shopOrderDTO.getGoodsName());
                    }
                }
            }
        }
        return iPage;
    }

}
